package com.cpms.framework.common.utils;

import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.StandardPBEByteEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;

/**
 * @description: jasypt加解密工具类
 * @author: gulang
 * @time: 2021/6/7 19:01
 */
public class CsJasyptUtils {

    /**
     * Jasypt生成加密结果
     *
     * @param jasyptPwd 配置文件中设定的加密密码 jasypt.encryptor.password
     * @param value    待加密值
     * @return
     */
    public static String encryptPwd(String jasyptPwd, String value) {
        PooledPBEStringEncryptor encryptOr = new PooledPBEStringEncryptor();
        encryptOr.setConfig(cryptOr(jasyptPwd));
        return encryptOr.encrypt(value);
    }

    /**
     * 解密
     *
     * @param jasyptPwd 配置文件中设定的加密密码 jasypt.encryptor.password
     * @param value    待解密密文
     * @return
     */
    public static String decyptPwd(String jasyptPwd, String value) {
        PooledPBEStringEncryptor encryptOr = new PooledPBEStringEncryptor();
        encryptOr.setConfig(cryptOr(jasyptPwd));
        return encryptOr.decrypt(value);
    }

    public static SimpleStringPBEConfig cryptOr(String jasyptPwd) {
        SimpleStringPBEConfig config = new SimpleStringPBEConfig();
        config.setPassword(jasyptPwd);
        config.setAlgorithm(StandardPBEByteEncryptor.DEFAULT_ALGORITHM);
        config.setKeyObtentionIterations("1000");
        config.setPoolSize("1");
        config.setProviderName("SunJCE");
        config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
        config.setStringOutputType("base64");
        return config;
    }
}
